package com.tiezhu.springdemo.mqtt;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tiezhu.springdemo.bean.FeedHistory;
import com.tiezhu.springdemo.bean.PicApiBean;
import com.tiezhu.springdemo.mapper.HistoryMapper;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HanderThread implements Runnable{

    String topic;
    String content;

    private HistoryMapper historyMapper;

    private static String url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/animal";
    private static String apiKey = "lcXsGih4GErtr2obtsmnX4zY";
    private static String secretKey = "fIkKG7IZSBY8AaBK5udZzfeMummy2QN5";

    public HanderThread(String topic,String content) {
        this.topic = topic;
        this.content = content;
    }

    @Override
    public void run() {
        this.historyMapper = BeanContext.getApplicationContext().getBean(HistoryMapper.class);
        if (this.content.length() > 0 ){
            JSONObject jsonObject = JSON.parseObject(content);
            String cmd = jsonObject.getString("cmd");
            System.out.println(topic.indexOf("device/"));
            System.out.println(topic.lastIndexOf("/client"));
            String username = topic.substring( topic.indexOf("device/") + 7 , topic.lastIndexOf("/client") );
            System.out.println(username);
            switch (cmd){
                case "feed":{
                    String isSuccess = jsonObject.getString("isSuccess");
                    Integer i = Integer.valueOf(isSuccess);
                    if (i == 1) {
                        System.out.println(1);
                        String result = addHistory(true, username);
                        System.out.println(result);
                        return;
                    }
                    String result = addHistory(false, username);
                    System.out.println(result);
                    return;

                }
                case "pic": {
                    String imgStr = jsonObject.getString("pic");
                    String result = animal(imgStr);
                    PicApiBean picApiBean = JSON.parseObject(result, PicApiBean.class);
                    List<PicApiBean.ResultBean> result1 = picApiBean.getResult();
                    PicApiBean.ResultBean resultBean = result1.get(0);
                    int is = resultBean.getName().indexOf("猫");
                    if (is != 0){
                        Map<String,Object> map = new HashMap<>();
                        map.put("cmd","pet");
                        map.put("data","cat");
                        String json = JSONObject.toJSONString(map);
                        MqttClientUtil.publish_common("app/admin/client",json);
                    }
                }
            }
        }
    }

    private String addHistory(boolean isSuccess,String username) {
        if (isSuccess){
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
            List<FeedHistory> list = historyMapper.queryHistoryToday(df.format(new Date()),username);
            FeedHistory feedHistory = new FeedHistory("1",df.format(new Date()),username,1);
            if (list.size() == 0){
                historyMapper.addHistory(feedHistory);
            }else {
                historyMapper.updateHistory(feedHistory);
            }
            return "数据持久化成功";
        }
        return "数据格式错误";
    }


    public static String animal(String imgStr){
        String imgParam = URLEncoder.encode(imgStr);
        String param = "image="+imgParam;
        try {
            String result = HttpUtil.post(url,getAuth(apiKey,secretKey),param);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return "api调用出错";
        }
    }

    public static String getAuth(String ak, String sk) {
        // 获取token地址
        String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
        String getAccessTokenUrl = authHost
                // 1. grant_type为固定参数
                + "grant_type=client_credentials"
                // 2. 官网获取的 API Key
                + "&client_id=" + ak
                // 3. 官网获取的 Secret Key
                + "&client_secret=" + sk;
        try {
            URL realUrl = new URL(getAccessTokenUrl);
            // 打开和URL之间的连接device/admin/feed
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.err.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String result = "";
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            /**
             * 返回结果示例
             */
            System.err.println("result:" + result);
            org.json.JSONObject jsonObject = new org.json.JSONObject(result);
            String access_token = jsonObject.getString("access_token");
            return access_token;
        } catch (Exception e) {
            System.err.printf("获取token失败！");
            e.printStackTrace(System.err);
        }
        return null;
    }

}
